import jieba from "@node-rs/jieba";
import rawWordDict from "@/../data/chinese-dictionary-main/word/word.json";
import rawCharDict from "@/../data/chinese-dictionary-main/character/char_base.json";

const wordDict = rawWordDict.reduce((ans, cur) => {
  ans.set(cur.word, cur);
  return ans;
}, new Map<string, any>());
const charDict = rawCharDict.reduce((ans, cur) => {
  ans.set(cur.char, cur);
  return ans;
}, new Map<string, any>());

const getPinyinWithDict = (str: string) => wordDict.get(str)?.pinyin;
const getPinyinWithoutDict = (str: string) => charDict.get(str)?.pinyin;

export function getWordDetails(content: string) {
  const words = jieba.cut(content, false);

  const wordsDetails: Array<{ word: string; pinyin?: string[] }> = [];

  for (const word of words) {
    const goodResult = getPinyinWithDict(word);
    if (goodResult) {
      wordsDetails.push({
        word,
        pinyin: [goodResult],
      });
    } else {
      const chars = word.split("");
      for (const char of chars) {
        const normalResult = getPinyinWithoutDict(char);
        wordsDetails.push({
          word: char,
          pinyin: normalResult,
        });
      }
    }
  }

  return wordsDetails;
}
